//
//  LaunchViewModel.swift
//  mmda
//
//  Created by 李陆涛 on 2018/4/23.
//  Copyright © 2018年 mmda. All rights reserved.
//

import UIKit

class LaunchViewModel: NSObject {

    
    var loadSuccess:(()->Void)?
    
    var loadFaild:((String)->Void)?
    
    func start() {
        
        NetAPI.now.request() {
            
            [weak self] response, errmsg in
            guard let `self` = self else { return }
            
            guard let res = response as? Dictionary<String, Any> else {
                
                return
            }
            
            AppManager.share.secret = res["secret"] as? String
            
            AppManager.share.serverTime = res["time"] as? Int ?? 0
            
            NetAPI.first.request(AppModel.self, completion: {
                
                [weak self] response, errmsg in
                guard let `self` = self else { return }
                
                if let model = response as? AppModel {
                    AppManager.share.appModel = model

                    self.autoLogin()

                } else {
                    
                    self.loadFaild?(errmsg ?? "网络加载失败")
                }
            })
        }
    }
    
    
    func autoLogin() {
        
        guard let mobile = AppManager.share.mobile, let code = AppManager.share.code else {
            
            self.loadSuccess?()
            return
        }
        
        NetAPI.checklogincode(mobile: mobile, code: code).request {
            
            [weak self] response, errmsg in
            guard let `self` = self else { return }
            
            self.loadSuccess?()
            
            guard let res = response as? Dictionary<String,Any> else {
                return
            }
            
            AppManager.share.token = res["token"] as? String
        }
    }
    
}
